<template>
  <div class="product-form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3 class="form-title">商品信息表单</h3>
        </div>
      </template>
      
      <el-form 
        label-width="120px" 
        class="product-form"
        :model="product"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品名称">
              <el-input 
                v-model="product.name"
                placeholder="请输入商品名称"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="所属分类">
              <el-select 
                v-model="product.cateId"
                placeholder="请选择商品分类"
                clearable
              >
                <el-option
                  v-for="item in catgorys"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="商品图片">
              <el-upload
                class="image-uploader"
                action="http://localhost/group1/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <div class="upload-wrapper">
                  <img v-if="imageUrl" :src="imageUrl" class="preview-image" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon">
                      <Plus />
                    </el-icon>
                    <div class="upload-text">点击上传图片</div>
                  </div>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="售价 (元)">
              <el-input-number
                v-model="product.salePrice"
                :min="0"
                :precision="2"
                step="0.01"
                placeholder="请输入售价"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="成本 (元)">
              <el-input-number
                v-model="product.costPrice"
                :min="0"
                :precision="2"
                step="0.01"
                placeholder="请输入成本"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="商品描述">
              <el-input
                v-model="product.description"
                type="textarea"
                :rows="4"
                placeholder="请输入商品描述"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item class="action-buttons">
          <el-button 
            type="primary" 
            @click="commitproduct"
            :disabled="!cancommit"
          >
            保存商品
          </el-button>
          <el-button 
            type="text" 
            @click="goback"
          >
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import axios from 'axios'
import router from '@/router'

// 状态管理
const imageUrl = ref('')
const catgorys = ref([{ id: 0, name: '', parentId: 0 }])
const cancommit = ref(true)

// 商品数据
const product = reactive({
  name: '',
  description: '',
  salePrice: 0,
  costPrice: 0,
  cateId: '',
  picUrl: ''
})

// 生命周期钩子
onMounted(() => {
  getCatgorys()
})

// 获取商品分类
function getCatgorys() {
  axios.get('/public/categorys').then(res => {
    catgorys.value = res.data.data || []
  }).catch(error => {
    ElMessage.error('获取商品分类失败，请稍后重试')
    console.error('获取商品分类失败:', error)
  })
}

// 图片上传处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  cancommit.value = true
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  product.picUrl = response
  ElMessage.success('图片上传成功')
  console.log('上传成功的图片URL:', response)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  cancommit.value = false
  
  const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/jpg'
  const isPNG = rawFile.type === 'image/png'
  const isLt5M = rawFile.size / 1024 / 1024 < 5
  
  if (!(isJPG || isPNG)) {
    ElMessage.error('图片格式必须为JPG或PNG')
    return false
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  
  return true
}

// 提交商品信息
function commitproduct() {
  // 简单验证
  if (!product.name) {
    ElMessage.warning('请输入商品名称')
    return
  }
  
  if (!product.cateId) {
    ElMessage.warning('请选择商品分类')
    return
  }
  
  if (!product.salePrice || product.salePrice <= 0) {
    ElMessage.warning('请输入有效的售价')
    return
  }
  
  if (!product.picUrl) {
    ElMessage.warning('请上传商品图片')
    return
  }
  
  axios.post('/products', product).then(res => {
    if (res.data.code * 1 === 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(res.data.message || '保存失败，请稍后重试')
    }
  }).catch(error => {
    ElMessage.error('保存失败，请稍后重试')
    console.error('保存商品失败:', error)
  })
}

// 返回上一页
function goback() {
  router.back()
}
</script>

<style scoped>
.product-form-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  background-color: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding-bottom: 16px;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.product-form {
  padding: 16px 0;
}

.image-uploader {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.image-uploader:hover {
  border-color: var(--el-color-primary);
}

.upload-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: var(--el-text-color-placeholder);
}

.upload-icon {
  font-size: 28px;
}

.upload-text {
  font-size: 12px;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 16px;
  padding-top: 20px;
}

.el-button {
  min-width: 100px;
}

.el-form-item__label {
  font-weight: 500;
}
</style>    